from sqlalchemy import *
from core.db import *
from core import *
import re

class qRoot(object):
	def __init__(self,word):
		self.word = word
	@staticmethod
	def giveAllRoots():
		return root_query.select()

class qWordRoot(object):
	def __init__(self, word_id=None,root_id=None):
		self.word_id = word_id
		self.root_id = root_id

root_table = Table('root_table',metadata,
		Column('id',Integer,primary_key=True),
		Column('word',String),
		Column('fa',String))
word_root_table = Table('word_root_table', metadata,
		Column('id', Integer, primary_key=True),
		Column('word_id',Integer,ForeignKey("word_table.id")),
		Column('root_id',Integer,ForeignKey("root_table.id")),
		Column('fa',String))

root_mapper = mapper(qRoot,root_table)
root_query = session.query(qRoot)
word_root_mapper = mapper(qWordRoot,word_root_table,properties={
	'word':relation(qpath.qWord,backref='roots'),
	'root':relation(qRoot,backref='words')})
word_root_query = session.query(qWordRoot)


def isSupportQuery(query,domain=""):
	r = re.compile("^\s*root{([^}]*)}\s*$").search(query)
	return (r != None)
	
def start_filter(sureQ,ayeQ,q):
	log.logger.debug('servers.root.start_filter(%s,%s,%s)' % (sureQ,ayeQ,q))
	r = re.compile("^\s*root{([^}]*)}\s*$").search(q)
	query = r.group(1)
	result = []
	root_ids = [root.id for root in root_query.select(qRoot.c.word == query)]
	if len(root_ids)==0:
		return []
	ww = set([word_root.word for word_root in word_root_query.select(qWordRoot.c.root_id.in_(root_ids))])
	if len(ww)==0:
		return []
	log.logger.debug('	roots:%d' % len(root_ids))
	log.logger.debug('	words:%d' % len(ww))
	for word in ww:
		if qpath.isWordInQPath(word,sureQ,ayeQ):
			result.append(word)
	log.logger.debug('	result:%d' % len(result))		
	return result		

def filter(query,domain):
	"""
	will filter queries with format
	"root{REGULAR_EXPRESSION}" on domain and return results
	"""
	r = re.compile("^\s*root{([^}]*)}\s*$").search(query)
	query = r.group(1)
	result = []
	d1 = []
	for d in domain:
		if isinstance(d,qpath.qAye) :
			d1 = d1 + [w for w in d.words]
		if isinstance(d,qpath.qSure) :
			for a in d.ayat:
				d1 = d1 + [w for w in a.words]
		if isinstance(d,qpath.qWord) :
			d1.append(d)


	root_ids = [root.id for root in root_query.select(qRoot.c.word == query)]
	ww = set([word_root.word_id for word_root in word_root_query.select(qWordRoot.c.root_id.in_(root_ids))])
	word_ids = set([w.id for w in d1])	
	for id in  ww & word_ids:
		result.append(qpath.word_query.get(id))
	return result	

#	for x in d1:
#		this_root_ids = set([r.root.id for r in x.roots])
#		if len(this_root_ids & root_ids) > 0:
#			result.append(x)
#	return result
log.logger.info("adding root module to qpath server")
qpath.server_isSupports.append(isSupportQuery)
qpath.server_filter.append(filter)

qpath.server_isStartSupports.append(isSupportQuery)
qpath.server_start_filter.append(start_filter)

if __name__ == "__main__":
	pass
